package com.leetroll.app.controller;

import com.leetroll.api.service.ItemService;
import com.leetroll.common.bean.ApiResponse;
import com.leetroll.common.enums.ECat;
import com.leetroll.common.vo.ItemVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static com.leetroll.common.enums.ECat.fromName;

@RestController
@RequestMapping("/search")
@Api(value = "SQL搜索相关接口", tags = {"SQL搜索相关接口"})
@Slf4j
public class SearchController {
    private final ItemService itemService;

    @Autowired
    public SearchController(ItemService itemService) {
        this.itemService = itemService;
    }

    @ApiOperation(value = "主搜索接口", notes = "主搜索接口")
    @GetMapping("/{cat}/{pageNumber}/{keyword}")
    public ApiResponse<List<ItemVO>> search(@PathVariable String cat, @PathVariable Integer pageNumber, @PathVariable String keyword) {
        ECat eCat = fromName(cat);
        if (eCat == null) {
            return ApiResponse.OK(new ArrayList<>());
        }
        return ApiResponse.OK(itemService.listItems(eCat.getCatId(), pageNumber, keyword));
    }

    @ApiOperation(value = "结果数量", notes = "结果数量")
    @GetMapping("/size/{cat}/{keyword}")
    public ApiResponse<Integer> search(@PathVariable String cat, @PathVariable String keyword) {
        ECat eCat = fromName(cat);
        if (eCat == null) {
            return ApiResponse.OK(0);
        }
        return ApiResponse.OK(itemService.totalSize(eCat.getCatId(), keyword));
    }
}
